'use strict';
console.log('Hello, Node.js');
const KuromojiAnalyzer = require("kuroshiro-analyzer-kuromoji");
const Kuroshiro = require("kuroshiro").default;
const kuroshiro = new Kuroshiro();

const ks = new Kuroshiro();
async function initKuroshiro(){
  await ks.init(new KuromojiAnalyzer());
}

async function mainProcess(){
  await initKuroshiro();
  console.log(await ks.convert('面影探して彷徨うだけ'));
}
// mainProcess();

/*
const fs = require('fs');
fs.readFile('C:/E/work_myself/python_study/nlp/content.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log('sy:'+data);
});
*/
const { open } = require('node:fs/promises');

function getLrcDict(){
  const contextDict = {};
  (async () => {
    
    const file = await open('./content.txt');
    var lines = file.readLines();
    var lines_no = 1;
    for await (const line of lines) {//这里做kanji to hira转换
      contextDict[lines_no++]=line;
    }
    return contextDict;
  })().then(function(result){
    co(result);
  });
};

//getLrcDict();

/** 主函数 */
function processJptoHira(){
  //遍历目录 获取文件列表
  //for 循环内 异步方式处理文件 
}

/** 转换单个文件 （该函数用来测试代码）*/
function transJpKanjiToHira(filename){
  //按行执行 异步/同步方式处理每一行

}

/** 转换lrc文件 */
function exeLrcFile(lrcfilename){

}

/** 封装转换后的内容到字典 */
async function packDictForTransJp(sentence){
  const j = {};
  await kuroshiro.init(new KuromojiAnalyzer())
  .then(function () {
    j['orig'] = sentence;
  }).then(function(){
    return kuroshiro.convert(sentence,{to:'hiragana',mode:'okurigana'});
  }).then(function(okhi){
    j['okhi'] = okhi;
    return kuroshiro.convert(sentence,{to:'hiragana',mode:'spaced'});
  }).then(function(hira){
    j['hira'] = hira;
    return kuroshiro.convert(sentence,{to:'romaji',mode:'spaced'});
  }).then(function(roma){
    j['roma'] = roma;
  }).then(function(){
    // console.log(j);
  });
  return j;
}


// packDictForTransJp('君の声も温もりも');

/** 简易转换单句 碎片式启用 */
function simpleTranslateJp(sentence){
  kuroshiro.init(new KuromojiAnalyzer())
  .then(function () {
    console.log(sentence);
  }).then(function(){
    return kuroshiro.convert(sentence,{to:'hiragana',mode:'okurigana'});
  }).then(function(result){
    console.log(result);
    return kuroshiro.convert(sentence,{to:'hiragana',mode:'spaced'});
  }).then(function(result){
    console.log(result);
    return kuroshiro.convert(sentence,{to:'romaji',mode:'spaced'});
  }).then(function(result){
    console.log(result);
  });
}


const want_to = 'トランプ大統領 ウクライナの停戦に向けた協議の進展に自信';

//simpleTranslateJp(want_to);
//const d = packDictForTransJp(want_to);

/** 转换普通文件 */
function exeTxtFile(filename) {
  const fs = require('fs');
  fs.readFile('./content.txt', 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    // console.log(data);
    var lines = data.split('\r\n');
    for (let inedx in lines) {
      packDictForTransJp(lines[inedx]);
    }
  });
}
// exeTxtFile('');

var str_txt = '[12345]君の声も温もりも';
// console.log(str_txt.slice(str_txt.indexOf(']')+1));
/** 拼接markdown table表头 */
function packMarkdownTableHead(...args){
  let h = '|';
  let d = '|';
  for (let i of args){
    h += `${i}|`;
    d += `---|`;
  }
  return `${h}\n${d}`;
}
/** 拼接markdown table内容 */
function packMarkdownTableContent(...args){
  let c = '|'
  for (let i of args){
    c += `${i}|`;
  }
  return c;
}
// console.log(packMarkdownTableHead('timestamps','orig','fenci','hira','roma'));
// console.log(packMarkdownTableContent('1','2','3','4','5'));

const testFenci = '心魅かれてく'.replace(' ','');
function testKuromoji(){
  const Kuromoji = require('kuromoji');
  // 用于存储分词结果的局部变量
  let tokenizationResults = [];
  // 创建 Kuromoji 分词器
  Kuromoji.builder({ dicPath: './node_modules/kuromoji/dict' }).build((err, tokenizer) => {
    if (err) {
      console.error(err);
      return;
    }
  
    // 按句子分割文本（简单按句号分割，实际可能更复杂）
    // const sentences = data.split('。');
    const sentences =[testFenci];
    sentences.forEach((sentence) => {
      if (sentence.trim() !== '') {
        const tokens = tokenizer.tokenize(sentence);
        const tokenText = tokens.map((token) => token.surface).join(' ');
        tokenizationResults.push(tokens);
      }
    });
    console.log(tokenizationResults);
  });
}

function testWanakana(){
  const wanakana = require('wanakana');
  let tokens = wanakana.tokenize(testFenci).join(' ');
  let hira = wanakana.toHiragana(tokens);
  console.log(tokens);
  // console.log(hira)
}
function testKuromojin(){
  const kuromojin = require('kuromojin');
  kuromojin.tokenize(testFenci).then(tokens => {
    for (let t of tokens){
      let l = '|';
      for (let k in t){
        l += `${t[k]}|`;
      }
      console.log(l);
    }
  });
}

// testWanakana();
// testKuromoji();
// testKuromojin();
const { program } = require('commander');
/**
 * -m --method 要执行的函数名
 * -a --methodargs 以(arg1,arg2,arg3,...)形式给出要执行的函数所需参数
 */
program.version('1.0','-v --vers')
.option('-m,--method <string>','especial method name')
.option('-a,--methodargs <string>','input args with style: (arg1,arg2,arg3,...)')
.parse();
const options = program.opts();
console.log(options)

if(options.method == 'mainProcess'){
  mainProcess();
}